﻿namespace Vibstudio.NetConfigurator.UI
{
    #region Namespaces

    using System;
    using System.Threading;
    using System.Windows;

    #endregion

    public partial class App
    {
        #region Static Fields

        private static readonly SingleInstance singleInstance =
            new SingleInstance(new Guid("24D910A1-1F03-44BA-85A0-BE7BC2655FFE"));

        #endregion

        #region Methods

        protected override void OnStartup(StartupEventArgs e)
        {
            if (!singleInstance.IsFirstInstance)
            {
                MessageBox.Show("L'applicazione è già in esecuzione!",
                                Enum.GetName(typeof(MessageBoxImage), MessageBoxImage.Warning),
                                MessageBoxButton.OK,
                                MessageBoxImage.Warning);

                Environment.Exit(0);
            }
        }

        #endregion

        private class SingleInstance : IDisposable
        {
            #region Fields

            private readonly Guid _identifier;

            private readonly bool _ownsMutex;

            private Mutex _mutex;

            #endregion

            #region Ctor(s)

            public SingleInstance(Guid id)
            {
                _identifier = id;
                _mutex = new Mutex(true, _identifier.ToString(), out _ownsMutex);
            }

            #endregion

            #region Public Properties

            public bool IsFirstInstance
            {
                get { return _ownsMutex; }
            }

            #endregion

            #region Public Methods and Operators

            public void Dispose()
            {
                if (_mutex != null && _ownsMutex)
                {
                    _mutex.ReleaseMutex();
                    _mutex = null;
                }
            }

            #endregion
        }
    }
}
